package com.txt.listener;


import com.txt.properties.RedisProperties;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;


@Slf4j
@Component
public class RedisListener implements MessageListener {
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private RedisProperties redisProperties;
    @Override
    public void onMessage(Message message, byte[] bytes) {
        RedisSerializer<?> serializer = redisTemplate.getStringSerializer();
        String channel = String.valueOf(serializer.deserialize(message.getChannel()));
        String key = String.valueOf(serializer.deserialize(message.getBody()));

        if (MessageFormat.format("__keyevent@{0}__:expired", redisProperties.getDatabase()).equals(channel)) {
            String format = MessageFormat.format("key: {0} 已过期", key);
            log.info(format);
        }

    }
}
